package com.pig4cloud.pig.module.controller.mer;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.mybatis.page.PageUtils;
import com.pig4cloud.pig.common.mybatis.page.TableDataInfo;
import com.pig4cloud.pig.common.security.service.PigUser;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import com.pig4cloud.pig.module.api.entity.excel.MerEggSettlementExcel;
import com.pig4cloud.pig.module.api.entity.mer.MerEggSettlement;
import com.pig4cloud.pig.module.api.entity.wx.WxUser;
import com.pig4cloud.pig.module.service.mer.IMerEggSettlementService;
import com.pig4cloud.pig.module.service.mer.IMerService;
import com.pig4cloud.pig.module.service.wx.IWxTemplateService;
import com.pig4cloud.pig.module.service.wx.IWxUserService;
import com.vdurmont.emoji.EmojiParser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.*;

/**
 * 结算金额Controller
 *
 * @author ruoyi
 * @date 2022-05-20
 */
@Validated
@Api(value = "结算金额控制器", tags = {"结算金额管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/mer/egg/settlement")
public class MerEggSettlementController {

    private final IMerEggSettlementService merEggSettlementService;
    private final IMerService merService;
	private final IWxUserService wxUserService;
	private final IWxTemplateService wxTemplateService;


	/**
     * 查询结算金额列表
     */
    @ApiOperation("查询结算金额列表")
    @PreAuthorize("@pms.hasPermission('module:eggsettle:list')")
    @GetMapping("/list")
    public TableDataInfo<MerEggSettlement> list(@Validated MerEggSettlement merEggSettlement) {
        QueryWrapper<MerEggSettlement> qw = new QueryWrapper<>();
		if(merEggSettlement.getMerId() != null){
			qw.eq("mer_id",merEggSettlement.getMerId());
		}
		if(merEggSettlement.getCheckState() != null){
			qw.eq("check_state",merEggSettlement.getCheckState());
		}
		if(merEggSettlement.getPayState() != null){
			qw.eq("pay_state",merEggSettlement.getPayState());
		}
		if(StrUtil.isNotEmpty(merEggSettlement.getBeginDate())){
			qw.between("create_time", merEggSettlement.getBeginDate() + " 00:00:00",merEggSettlement.getEndDate() + " 23:59:59");
		}
		qw.orderByDesc("create_time");
        TableDataInfo<MerEggSettlement> td = PageUtils.buildDataInfo(merEggSettlementService.page(PageUtils.buildPage(),qw));
        List<MerEggSettlement> list = td.getData();
        if(CollUtil.isNotEmpty(list)){
            for (MerEggSettlement settle : list){
                WxUser wxUser = wxUserService.getById(settle.getUserId());
                if(wxUser!=null){
                    settle.setNickName(EmojiParser.parseToUnicode(wxUser.getNickName()));
                }
            }
        }
        return td;
    }



	/**
	 * 查询结算金额列表
	 */
	@ApiOperation("查询结算金额列表")
	@PreAuthorize("@pms.hasPermission('module:eggsettle:list')")
	@GetMapping("/tongji/list")
	public TableDataInfo<MerEggSettlement> tongjiList(@Validated MerEggSettlement merEggSettlement) {
		Map<String,Object> map = new HashMap<>();
		if(merEggSettlement.getMerId() != null){
			map.put("mer_id",merEggSettlement.getMerId());
		}
		if(StrUtil.isNotEmpty(merEggSettlement.getBeginDate())){
			map.put("begin_time", merEggSettlement.getBeginDate() + " 00:00:00");
			map.put("end_time", merEggSettlement.getEndDate() + " 23:59:59");
		}
		TableDataInfo<MerEggSettlement> td = PageUtils.buildDataInfo(merEggSettlementService.selectSettlementByMerId(PageUtils.buildPage(),map));
		return td;
	}



	/**
	 * 导出结算金额列表
	 */
	@ApiOperation("导出结算金额列表")
	@PreAuthorize("@pms.hasPermission('module:eggsettle:export')")
	@SysLog("结算金额")
	@GetMapping("/exportTotal")
	public List exportTotal(@Validated MerEggSettlement merEggSettlement) {
		Map<String,Object> map = new HashMap<>();
		if(merEggSettlement.getMerId() != null){
			map.put("mer_id",merEggSettlement.getMerId());
		}
		if(StrUtil.isNotEmpty(merEggSettlement.getBeginDate())){
			map.put("begin_time", merEggSettlement.getBeginDate() + " 00:00:00");
			map.put("end_time", merEggSettlement.getEndDate() + " 23:59:59");
		}

		List<MerEggSettlementExcel> list = merEggSettlementService.selectSettlementTongjiByMerId(map);
		// ExcelUtil<MerEggSettlementExcel> util = new // ExcelUtil<>(MerEggSettlementExcel.class);
		return  list;// util.exportExcel(list, "鸡蛋结算统计金额");
	}

	/**
     * 导出结算金额列表
     */
    @ApiOperation("导出结算金额列表")
    @PreAuthorize("@pms.hasPermission('module:eggsettle:export')")
    @SysLog("结算金额")
    @GetMapping("/export")
    public List export(@Validated MerEggSettlement merEggSettlement) {
		QueryWrapper<MerEggSettlement> qw = new QueryWrapper<>();

		if(merEggSettlement.getMerId() != null){
			qw.eq("mer_id",merEggSettlement.getMerId());
		}
		if(merEggSettlement.getCheckState() != null){
			qw.eq("check_state",merEggSettlement.getCheckState());
		}
		if(StrUtil.isNotEmpty(merEggSettlement.getBeginDate())){
			qw.between("create_time", merEggSettlement.getBeginDate() + " 00:00:00",merEggSettlement.getEndDate() + " 23:59:59");
		}
        List<MerEggSettlement> list = merEggSettlementService.list(qw);
		if(CollUtil.isNotEmpty(list)){
			for (MerEggSettlement settlement : list){

				//结算状态 0  - 待审核  1 - 已审核  2 - 已结算 3 - 已打款  4- 打款失败
				if(settlement.getState() == 0){
					settlement.setStateStr("待审核");
				} else if(settlement.getState() == 1){
					settlement.setStateStr("已审核");
				} else if(settlement.getState() == 2){
					settlement.setStateStr("已结算");
				} else if(settlement.getState() == 3){
					settlement.setStateStr("已打款");
				} else if(settlement.getState() == 4){
					settlement.setStateStr("打款失败");
				}

				//提现支付状态 0 - 待审核   1 - 支付成功  2 - 支付失败  3 - 拒绝支付
				if(settlement.getPayState() == 0){
					settlement.setPayStateStr("待审核");
				} else if(settlement.getPayState() == 1){
					settlement.setPayStateStr("支付成功");
				} else if(settlement.getPayState() == 2){
					settlement.setPayStateStr("支付失败");
				} else if(settlement.getPayState() == 3){
					settlement.setPayStateStr("拒绝支付");
				}
			}
		}
        // ExcelUtil<MerEggSettlement> util = new // ExcelUtil<MerEggSettlement>(MerEggSettlement.class);
        return  list;// util.exportExcel(list, "结算金额");
    }

    /**
     * 获取结算金额详细信息
     */
    @ApiOperation("获取结算金额详细信息")
    @PreAuthorize("@pms.hasPermission('module:eggsettle:query')")
    @GetMapping("/{id}")
    public R<MerEggSettlement> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        MerEggSettlement merEggSettlement = merEggSettlementService.getById(id);
        return R.ok(merEggSettlement);
    }

    /**
     * 新增结算金额
     */
    @ApiOperation("新增结算金额")
    @PreAuthorize("@pms.hasPermission('module:eggsettle:add')")
    @SysLog("结算金额")

    @PostMapping()
    public R<Void> add(@Valid @RequestBody MerEggSettlement merEggSettlement) {
        return R.okByRow(merEggSettlementService.save(merEggSettlement) ? 1 : 0);
    }

    /**
     * 修改结算金额
     */
    @ApiOperation("修改结算金额")
    @PreAuthorize("@pms.hasPermission('module:eggsettle:edit')")
    @SysLog("结算金额")

    @PutMapping()
    public R<Void> edit(@Valid @RequestBody MerEggSettlement merEggSettlement) {
        PigUser sysUser = SecurityUtils.getUser();
        if(merEggSettlement.getState() == 0){
			merEggSettlement.setCheckSysUserId(sysUser.getId());
			merEggSettlement.setCheckSysUserName(sysUser.getName());
			merEggSettlement.setCheckTime(new Date());
		}else if(merEggSettlement.getState() == 1){
			merEggSettlement.setSubmitSysUserId(sysUser.getId());
			merEggSettlement.setSubmitUserName(sysUser.getName());
			merEggSettlement.setSubmitTime(new Date());
		}
        boolean bl = false;
        if(merEggSettlement.getState() == 1){
			Map<String,Object> map = merEggSettlementService.checkRecord(merEggSettlement);
			if(map.containsKey("result_code")){
				if(map.get("result_code").equals("SUCCESS")){
					return R.okByRow(1);
				} else {
					return R.failed(map.get("err_code_des").toString());
				}
			}
			return R.okByRow(0);
        }else{
			if(merEggSettlement.getState() == 0){
				merEggSettlement.setState(1);
			}
            bl = merEggSettlementService.updateById(merEggSettlement);
            if(bl){
            	if(merEggSettlement.getState() == 1){
            		//发送推送给财务部门，通知结算
					wxTemplateService.sendWxMsgEggSettleSubmit(merEggSettlement,merEggSettlement.getPayMoney().doubleValue());
				}
			}
        }
        return R.okByRow(bl ? 1 : 0);
    }

    /**
     * 删除结算金额
     */
    @ApiOperation("删除结算金额")
    @PreAuthorize("@pms.hasPermission('module:eggsettle:remove')")
    @SysLog("结算金额")
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {
        return R.okByRow(merEggSettlementService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }

	/**
	 * 批量修改状态
	 */
	@ApiOperation("修改结算金额")
	@PreAuthorize("@pms.hasPermission('module:eggsettle:edit')")
	@SysLog("结算金额")

	@PutMapping("/resetPay")
	public Integer resetPay() {
		QueryWrapper<MerEggSettlement> qw=new QueryWrapper<>();
		qw.eq("pay_state",2);
		TableDataInfo<MerEggSettlement> td = PageUtils.buildDataInfo(merEggSettlementService.page(PageUtils.buildPage(),qw));
		List<MerEggSettlement> list = td.getData();
		for(MerEggSettlement list1:list){
			list1.setState(0);
			list1.setPayState(0);
			R.okByRow(merEggSettlementService.updateById(list1));
		}
		return 1;
	}

	@ApiOperation("查询结算金额列表")
	@PreAuthorize("@pms.hasPermission('module:eggsettle:list')")
	@GetMapping("/settlementNum")
	public List settlementNum(@Validated MerEggSettlement merEggSettlement) {
		QueryWrapper<MerEggSettlement> qw = new QueryWrapper<>();
		if(StrUtil.isNotEmpty(merEggSettlement.getBeginDate())){
			qw.between("create_time", merEggSettlement.getBeginDate() + " 00:00:00",merEggSettlement.getEndDate() + " 23:59:59");
		}
		TableDataInfo<MerEggSettlement> td = PageUtils.buildDataInfo(merEggSettlementService.page(PageUtils.buildPage(),qw));
		List<MerEggSettlement> list = td.getData();
		Double settlementMoney=0.00;
		Integer settlementEgg=0;
		for (MerEggSettlement list1:list){
			settlementEgg+=list1.getTotalCount();
			settlementMoney+=list1.getRegPayMoney().doubleValue();
		}
		if (list.size()!=0){
			Integer settlement=list.size();
			double one = (double)Math.round(settlementMoney*100)/100;
			List list2 = new ArrayList<>();
			list2.add(settlement);
			list2.add(settlementEgg);
			list2.add(one);
			return list2;
		}else {
			List list2 = new ArrayList<>();
			list2.add(0);
			list2.add(0);
			list2.add(0);
			return list2;
		}
	}

}
